// ignore_for_file: file_names, must_be_immutable, constant_identifier_names, slash_for_doc_comments, avoid_unnecessary_containers, prefer_const_constructors, unnecessary_cast, sized_box_for_whitespace, prefer_function_declarations_over_variables, overridden_fields, annotate_overrides, prefer_const_literals_to_create_immutables, unnecessary_null_comparison, deprecated_member_use

import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:mybase/base/tool/globalMethod/FFListen.dart';
import 'package:mybase/base/tool/globalMethod/FFSafeValue.dart';
import 'package:mybase/base/tool/pprint/FFLog.dart';
import 'package:mybase/base/tool/time/FFTime.dart';

class FFUIRefreshManager {
  // 单例公开访问点
  factory FFUIRefreshManager() => _sharedInstance();

  // 静态、同步、私有访问点
  static FFUIRefreshManager _sharedInstance() {
    return _instance;
  }

  // 静态私有成员，没有初始化
  static final FFUIRefreshManager _instance = FFUIRefreshManager._();

  // 私有构造函数
  FFUIRefreshManager._() {
    // 具体初始化代码
  }

  Map<String, ValueNotifier> _map = {};

  //随取一个与时间相关的id
  String getRandomID() {
    var nextInt = Random().nextInt(99999999);
    var nextInt2 = Random().nextInt(99999999);
    var sinceEpoch = DateTime.now().microsecondsSinceEpoch;
    return "$nextInt$nextInt2$sinceEpoch";
  }

  //final ValueNotifier<double> valueListenable = ValueNotifier(0);
  set<T>(String key, ValueNotifier<T> listen) {
    if (_map.containsKey(key)) {
      FFLog.warn("已经包含 key = $key");
      return;
    }

    _map[key] = listen;
  }

  reSet<T>(String key, ValueNotifier<T> listen) {
    ValueNotifier? value = getValue(key);
    value?.dispose();

    _map[key] = listen;
  }

  remove(String key) {
    ValueNotifier? value = getValue(key);
    value?.dispose();

    _map.remove(key);
  }

  ValueNotifier<T>? getValue<T>(String key) {
    return globalSafeValueFromMap<ValueNotifier<T>>(_map, key);
  }

  ValueListenableBuilder builder<T>(String key,
      Widget Function(BuildContext ctx, T tValue, Widget? child) builder) {
    ValueNotifier<T>? noti = getValue<T>(key);
    assert(
        noti != null, "key = ${key} 对应的值没有，请调用FFUIRefreshManager().set()方法设置");
    return globalValueListen<T>(valueListenable: noti!, builder: builder);
  }
}
